/*
 * Copyright (c) 2013, Inmite s.r.o. (www.inmite.eu).
 *
 * All rights reserved. This source code can be used only for purposes specified
 * by the given license contract signed by the rightful deputy of Inmite s.r.o.
 * This source code can be used only by the owner of the license.
 *
 * Any disputes arising in respect of this agreement (license) shall be brought
 * before the Municipal Court of Prague.
 */

package eu.inmite.harmony.lib.validations.form.validators;

import eu.inmite.harmony.lib.validations.form.Utils;
import eu.inmite.harmony.lib.validations.form.annotations.NotEmpty;
import eu.inmite.harmony.lib.validations.form.annotations.ValidatorFor;
import eu.inmite.harmony.lib.validations.util.LogUtil;

import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.lang.annotation.Annotation;

/**
 * @author Tomas Vondracek
 */
@ValidatorFor(NotEmpty.class)
public class NotEmptyValidator extends BaseValidator<CharSequence> {
    private static final String TAG = NotEmptyValidator.class.getName();

    @Override
    public boolean validate(Annotation annotation, CharSequence input) {
        final CharSequence inputToValidate;
        if (((NotEmpty) annotation).trim()) {
            inputToValidate = input.toString().trim();
        } else {
            inputToValidate = input;
        }
        return !Utils.isEmpty(inputToValidate);
    }

    @Override
    public String getMessage(Context context, Annotation annotation, CharSequence input) {
        final int messageId = ((NotEmpty) annotation).messageId();
        String message = null;
        if (messageId > 0) {
            try {
                message = context.getResourceManager().getElement(messageId).getString();
            } catch (IOException e) {
                LogUtil.error(TAG, "IOException " + e.toString());
            } catch (NotExistException e) {
                LogUtil.error(TAG, "NotExistException " + e.toString());
            } catch (WrongTypeException e) {
                LogUtil.error(TAG, "WrongTypeException " + e.toString());
            }
        }
        return message;
    }
}
